package com.lntea.netty.demo.diff.echo.aio;

import com.lntea.netty.demo.diff.echo.EchoConstant;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Calendar;

/**
 * Title: ReadCompletionHandler.java<br>
 * Description:  <br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/5 18:03
 */
public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer>{

    /** 异步对客户端通道 */
    private AsynchronousSocketChannel channel;

    public ReadCompletionHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte[] bytes = new byte[attachment.remaining()];
        attachment.get(bytes);
        String responseBody = "bad echo";
        try {
            String body = new String(bytes, "utf-8");
            // 处理客户端请求
            System.out.println(String.format("Echo Server receive msg: %s", body));
            if (EchoConstant.QUERY_TIME.equals(body)) {
                responseBody = Calendar.getInstance().getTime().toString();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        doWrite(responseBody);
    }

    /**
     * 输出返回
     * @param responseBody
     */
    private void doWrite(String responseBody) {
        if (responseBody != null && responseBody.trim().length() > 0) {
            byte[] bytes = responseBody.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    if (writeBuffer.hasRemaining()) {
                        channel.write(writeBuffer, writeBuffer, this);
                    }
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        exc.printStackTrace();
        try {
            channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
